package com.hzsk.lisence.config;

import com.hzsk.lisence.entity.LisenceUserEntity;
import com.hzsk.lisence.mapper.LisenceUserMapper;
import com.hzsk.lisence.util.JwtUtils;
import com.hzsk.lisence.util.RsaUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private LisenceUserMapper lisenceUserMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 如果不是映射到方法不拦截 直接通过
        boolean flag = true;
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //验证token
        if (StringUtils.isNoneBlank(token)){
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile(MyConfig.PUB).getPath());
                //解析令牌
                LisenceUserEntity infoFromToken = (LisenceUserEntity) JwtUtils.getInfoFromToken(token, publicKey, LisenceUserEntity.class);
                if (infoFromToken != null) {
                    String userAccount = infoFromToken.getUserAccount();
                    Integer account = lisenceUserMapper.isAccount(userAccount);
                    flag =  account > 0;
                }
            } catch (Exception e) {
                flag =  false;
            }
        }
        if (!flag){
            response.setContentType("text/plain;charset=UTF-8");
            // 返回响应字符串
            response.getWriter().write("token失效");
        }
        return flag;
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("执行了拦截器的postHandle方法");
    }



}
